package com.illtamer.infinite.morii.controller;

import com.illtamer.infinite.morii.service.TransportService;
import com.illtamer.infinite.morii.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
public class UploadController {

    @Resource(name = "transportService")
    private TransportService transportService;

    @RequestMapping("/upload")
    public String upload() {
        return "upload";
    }

    @RequestMapping(path = "/upload/file", method = RequestMethod.POST)
    public void uploadFile(@RequestParam("jar") MultipartFile jar, @RequestParam("pom") MultipartFile pom,
                           HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        final String groupId = request.getParameter("groupId");
        final String artifactId = request.getParameter("artifactId");
        final String version = request.getParameter("version");
        if (CommonUtil.isNull(groupId, artifactId, version, jar, pom))
            request.getRequestDispatcher("/upload").forward(request, response);
        if (jar.isEmpty() || pom.isEmpty())
            request.getRequestDispatcher("/upload").forward(request, response);

        transportService.upload(groupId, artifactId, version, jar.getBytes(), pom.getBytes());
        response.sendRedirect("/public/");
    }

}
